package com.fyt.ZhongYaoApp.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsFilterConfiguration {

    @Bean
    public CorsFilter corsFilter() {
        //1.添加CORS配置信息
        CorsConfiguration configuration = new CorsConfiguration();

        //允许所有源请求跨域，* 表示不限制
        configuration.addAllowedOrigin("*");

        //跨域请求默认不包含Cookie，设置为true可以包含Cookie
        configuration.setAllowCredentials(false);

        //允许所有方法跨域，或者设置请求方式GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE
        configuration.addAllowedMethod("*");

        //允许所有原始请求头信息
        configuration.addAllowedHeader("*");

        //允许暴露哪些头信息，为了安全问题不能设置成*，否则会报错：throw new IllegalArgumentException("'*' is not a valid exposed header value");
        configuration.addExposedHeader("");

        //设置请求有效时间
        configuration.setMaxAge(3600L);

        //2.添加映射路径，即允许对方可以访问本应用下的哪些请求接口，/** 表示所有请求
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**",configuration);

        //3.返回新的CorsFilter.
        return new CorsFilter(configSource);
    }
}

